<template>
  <div>
    <div class="topSearchThree">
      <div class="topSearchThreeLeft">
        <div>
          <p>名称:</p>
          <el-input
            v-model="couponName"
            :style="{ width: '160px', marginLeft: '20px' }"
            placeholder="名称"
          ></el-input>
        </div>
        <div style="margin-left: 10px">
          <p style="margin-right: 20px">日期选择:</p>
          <el-date-picker
            v-model="searchTime"
            type="daterange"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="chooseTimeHandle"
          >
          </el-date-picker>
        </div>
      </div>
      <div class="topSearchThreeRight">
        <el-button
          type="primary"
          :style="{ marginLeft: '20px' }"
          @click="handleSearch"
        >
          查询
        </el-button>
        <el-button :style="{ marginLeft: '20px' }" @click="resettingHandle">
          重置
        </el-button>
      </div>
    </div>
    <!-- 商家优惠卷优惠卷 -->
    <div class="goodsselloutbox">
      <!-- <div>
        <el-input
          v-model="couponName"
          :style="{
            width: '160px',
            marginLeft: '20px',
            marginRight: '20px',
          }"
          placeholder="名称"
          :clearable="true"
          @clear="Refresh"
        ></el-input>

        <el-button
          v-model="searchShop"
          :style="{ marginLeft: '20px' }"
          circle
          icon="el-icon-search"
          @click="handleSearch"
        ></el-button>
      </div> -->
      <!-- <div class="SecondRow">
        <div>
          <el-button round size="mini" @click="addcoupon">新增优惠卷</el-button>
          <el-button
            :style="{ marginLeft: '20px' }"
            round
            size="mini"
            @click="Refresh"
            >刷新
          </el-button>
        </div>
      </div>
      <分割线 
      <el-divider></el-divider> -->
      <div class="SecondRow">
        <div class="SecondRowLeft">
          <el-button type="primary" @click="addcoupon"> 新增优惠卷 </el-button>
          <el-button :disabled="isButtonDisabled" @click="bulkOperation(0)"
            >禁用</el-button
          >
          <el-button :disabled="isButtonDisabled" @click="bulkOperation(1)"
            >启用</el-button
          >
        </div>
        <div class="SecondRowRight">
          <el-button circle icon="el-icon-refresh-right" @click="Refresh">
          </el-button>
        </div>
      </div>
      <div class="DataTableDiv">
        <el-table
          v-loading="loading"
          :cell-style="{ 'text-align': 'center' }"
          :data="goodsList"
          :header-cell-style="{ 'text-align': 'center' }"
          border
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" min-width="60"></el-table-column>
          <el-table-column label="排序" prop="sort" min-width="60">
            <template slot-scope="scope">
              <div class="flex-container">
                <span class="flex-item">
                  {{ scope.$index + 1 }}
                </span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="名称" prop="name" min-width="140">
          </el-table-column>
          <el-table-column
            label="优惠卷金额/元"
            prop="methodAmount"
            min-width="140"
          >
            <template slot-scope="scope">
              <div class="flex-container">
                <span class="flex-item">
                  <p>{{ scope.row.methodAmount / 100 }}</p>
                </span>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="优惠卷数量/张"
            prop="publishTotalNumber"
            min-width="140"
          >
            <template slot-scope="scope">
              <div class="flex-container">
                <span class="flex-item">
                  <p v-if="scope.row.publishTotalNumber === -1">不限制</p>
                  <p v-else>{{ scope.row.publishTotalNumber }}</p>
                </span>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="可用订单金额/元"
            prop="useConditions"
            min-width="140"
          >
            <template slot-scope="scope">
              <div class="flex-container">
                <span class="flex-item">
                  <p>{{ scope.row.useConditions / 100 }}</p>
                </span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="领取方式" prop="type" min-width="140">
            <template slot-scope="scope">
              <div class="flex-container">
                <span class="flex-item">
                  <p>{{ getTypeText(scope.row.type) }}</p>
                </span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="有效时间" prop="startDate" min-width="220">
            <template slot-scope="scope">
              <div class="flex-container">
                <span class="flex-item">
                  <p>
                    {{ formatDate(scope.row.startDate) }}-{{
                      formatDate(scope.row.endDate)
                    }}
                  </p>
                </span>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="是否开启" prop="isEnabled" min-width="140">
            <template slot-scope="scope">
              <div class="flex-container">
                <el-switch
                  v-model="scope.row.isEnabled"
                  :active-value="1"
                  :inactive-value="0"
                  @change="isEnabledHandle(scope.row)"
                >
                </el-switch>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" min-width="258">
            <template slot-scope="scope">
              <el-button
                size="small"
                type="text"
                style="margin-right: 10px"
                @click="grantCouponHandle(scope.row)"
                >活动商品
              </el-button>
              <el-button
                size="small"
                type="text"
                @click="handleClick(scope.row)"
                >查看使用详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="paging">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="10"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </div>

    <!-- 添加/修改商品组件 -->
    <BusCouponAdd
      v-if="centerDialogVisible"
      :centerDialogVisible="centerDialogVisible"
      :enterType="enterType"
      :cancelSubmit="cancelSubmit"
      @cancelgoodesmodel="cancelgoodesmodel"
      @Refresh="Refresh"
    />
    <DiscountRecord
      v-if="centerDialogVisible2"
      :centerDialogVisibleUse="centerDialogVisible2"
      :couponId="couponId"
      @cancelgoodesmodel2="cancelgoodesmodel2"
    />
    <BusActiveGoods
      v-if="centerDialogVisible3"
      :currentRow="currentRow"
      :couponId="couponId"
      :centerDialogVisibleUse="centerDialogVisible3"
      @cancelgoodesmodel3="cancelgoodesmodel3"
    />
  </div>
</template>
<script>
import BusCouponAdd from "@/views/mall/managementend/memberList/components/Buscouponadd.vue";
import DiscountRecord from "@/views/mall/managementend/memberList/components/Discountrecord.vue";
import BusActiveGoods from "@/views/mall/managementend/memberList/components/Busactivegoods.vue";
import {
  QueryCouponList,
  EditCoupon,
  DeleteCoupon,
  QueryCouponDetail,
  batchUpdateCoupon,
} from "@/api/mallApi/managementend/coupon";

export default {
  name: "BusinessCoupon",
  components: {
    BusCouponAdd,
    DiscountRecord,
    BusActiveGoods,
  },
  data() {
    return {
      table: "1", //默认先调用的是平台优惠卷
      activeName: "1",
      searchTime: "",
      storeStatus: "", //店铺状态搜索
      mallCode: "", //店铺名称搜索
      // 添加/修改 商品弹窗
      centerDialogVisible: false,
      centerDialogVisible2: false,
      centerDialogVisible3: false,
      currentRow: {}, // 保存当前行数据
      enterType: 0, // 默认值为1，表示从编辑按钮进入
      cancelSubmit: 0, //商品审核不能确定修改
      searchShop: "",
      goodsList: [],
      selectedRows: [], // 表格 多选内容
      isButtonDisabled: false, // checkbox 联动按钮
      currentPage: 1, // 分页
      total: 0,
      pageSize: 10,
      loading: false,
      couponName: "",
      couponId: null,
    };
  },
  methods: {
    //重置
    resettingHandle() {
      this.couponName = null;
      this.searchTime = "";
      this.Refresh();
    },
    formatDate(originalTimeString) {
      if (!originalTimeString) {
        return ""; // or any default value you prefer
      }
      const [datePart, timePart] = originalTimeString.split(" ");
      const [year, month, day] = datePart.split("-");
      return `${year}.${month}.${day}`;
    },
    grantCouponHandle(e) {
      //console.log('123',e);
      //打开弹窗组件
      this.couponId = e.id;
      this.centerDialogVisible3 = true;
      this.currentRow = e;
      // ////console.log("345", this.currentRow);
    },
    bulkOperation(e) {
      const data = {
        ids: this.selectedRows.map((item) => item.id),
        isEnabled: e,
      };
      batchUpdateCoupon(data).then((res) => {
        if (res.code !== "00000") return;
        this.Refresh();
        this.$message({
          message: "优惠卷状态修改成功！",
          type: "success",
        });
      });
    },
    chooseTimeHandle(e) {
      if (e === null && this.searchTime === null) {
        this.getCouponList();
      }
    },
    delectClickHandle(e) {
      this.$confirm("是否删除该优惠卷信息？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          const params = {
            ids: [e.id],
          };
          DeleteCoupon(params).then((res) => {
            if (res.code === "00000") {
              this.$message({
                message: "删除成功",
                type: "success",
              });
              this.Refresh();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    isEnabledHandle(e) {
      EditCoupon(e).then((res) => {
        if (res.code !== "00000") return;
        this.Refresh();
        this.$message({
          message: "优惠卷开启成功！",
          type: "success",
        });
      });
    },
    addcoupon() {
      this.enterType = 1;
      this.centerDialogVisible = true; // 打开弹窗
    }, // 添加优惠卷
    Refresh() {
      this.getCouponList();
    },
    getTypeText(type) {
      switch (type) {
        case 1:
          return "发放卷";
        case 2:
          return "领取卷";
        default:
          return "未知";
      }
    },
    ClearAttributes() {}, // 清空 商品属性
    ClearCategory() {
      this.Refresh();
    }, // 清空 商品分类
    // 分页
    handleSizeChange(val) {
      this.pageSize = val;
      this.getCouponList();
    },
    handleCurrentChange(val) {
      // 分页
      this.currentPage = val;
      this.getCouponList();
    },
    handleSelectionChange(selection) {
      this.selectedRows = selection;
      //   ////console.log('this.selectedRows',this.selectedRows);
      // TODO 在这里进行相应的操作，如发起请求等
    }, // 表格多选
    async handleClick(row) {
      ////console.log(row);
      this.couponId = row.id;
      this.centerDialogVisible2 = true; // 打开弹窗
    },
    cancelgoodesmodel(data) {
      // 弹窗关闭时触发，可以在这里重置数据或进行其他操作
      this.centerDialogVisible = data;
      this.enterType = 0;
    },
    cancelgoodesmodel2(data) {
      // 弹窗关闭时触发，可以在这里重置数据或进行其他操作
      this.centerDialogVisible2 = data;
    },
    cancelgoodesmodel3(data) {
      // 弹窗关闭时触发，可以在这里重置数据或进行其他操作
      this.centerDialogVisible3 = data;
      this.currentRow = {};
    },
    // 获取商品列表
    getCouponList() {
      this.loading = true;
      const params = {
        searchBeginTime: "", //开始时间
        searchEndTime: "", //结束时间
        pageSize: this.pageSize, //分页：每页大小（默认10）
        pageNo: this.currentPage, //分页：第几页（从1开始）
        orderBy: "", //排序字段
        sortBy: "asc", //正序或者倒序排列（asc 或 desc）
        name: this.couponName, //优惠卷名称
        searchBeginTime: this.searchTime ? this.searchTime[0] : "",
        searchEndTime: this.searchTime ? this.searchTime[1] : "",
        // table: 2,
      };

      //   获取店铺列表
      QueryCouponList(params)
        .then((res) => {
          // console.log("查询优惠卷列表", res);
          if (res.code !== "00000") return;
          this.goodsList = res.data.rows;
          this.total = parseInt(res.data.totalRows);
          this.loading = false;
        })
        .catch((error) => {
          this.loading = false;
        });
    },
    // 获取商品分类列表
    // 搜索
    handleSearch() {
      this.currentPage = 1;
      this.getCouponList();
    },
  },
  created() {},
  mounted() {
    this.Refresh();
  },
  computed: {
    fifterdShop() {
      return this.goodsList.filter((item) => {
        return item.name.toLowerCase().includes(this.searchShop.toLowerCase);
      });
    },
  },
  watch: {
    selectedRows: {
      handler(newValue) {
        // 数组发生变化时，isButtonDisabled计算属性会重新计算，从而更新按钮的禁用状态
        this.isButtonDisabled = newValue.length === 0;
      },
      deep: true,
      immediate: true, // 立即执行处理函数
    },
  },
};
</script>

<style lang="scss">
.TongYiClass {
  background-color: #409eff;
  color: #fff;
  border: none;
  margin-right: 20px;
  &:hover {
    background-color: #439bf6;
    color: #fff;
  }
}

.BoHuiClass {
  background-color: #f56c6c !important ;
  color: #fff;
  border: none;
  &:hover {
    background-color: #ef7e7e;
    color: #fff;
  }
}
.el-tabs__active-bar {
  margin-left: 25px;
}
.el-tabs--bottom .el-tabs__item.is-bottom:nth-child(2),
.el-tabs--bottom .el-tabs__item.is-top:nth-child(2),
.el-tabs--top .el-tabs__item.is-bottom:nth-child(2),
.el-tabs--top .el-tabs__item.is-top:nth-child(2) {
  margin-left: 25px;
}
</style>
<style lang="scss" scoped>
.topSearchThree {
  width: 98%;
  margin: 1%;
  background-color: #fff;
  min-height: 75px;
  display: flex;
  justify-content: space-between;
  .topSearchThreeLeft {
    width: 1050px;
    display: flex;
    margin-top: 10px;
    margin-left: 10px;
    > div {
      display: flex;
      align-items: center;
      p {
        font-size: 14px;
      }
      margin-left: 10px;
    }
  }
  .topSearchThreeRight {
    width: 200px;
    display: flex;
    align-items: center;
  }
}
.goodsselloutbox {
  width: 98%;
  min-height: 750px;
  margin-top: 1%;
  margin-bottom: 1%;
  margin-left: 1%;
  background-color: #fff;
  overflow: hidden;

  .SecondRow {
    width: 100%;
    min-height: 65px;
    margin-top: 10px;
    display: flex;
    justify-content: space-between;
    .SecondRowLeft {
      margin-top: 10px;
      margin-left: 20px;
    }
    .SecondRowRight {
      margin-top: 10px;
      margin-right: 30px;
    }
  }

  .DataTableDiv {
    width: 98%;
    margin-left: 1%;
    margin-bottom: 15px;
    border: 1px solid #dcdee2;

    //表格
    .flex-container {
      display: flex;
      align-items: center; /* 垂直居中 */
      justify-content: space-around;

      > img {
        width: 70px;
        height: 70px;
      }

      .flex-item {
        width: 150px;
        height: 40px;
        -webkit-line-clamp: 2; /* 显示两行文本 */
        -webkit-box-orient: vertical;
        overflow: hidden;
      }
    }

    .TableAttrTem {
      display: flex;
      align-items: center;
      // justify-content: space-around;
      margin: 0 25px;
    }
  }

  .paging {
    width: 99%;
    height: 50px;
    margin-bottom: 20px;
    // background-color: antiquewhite;
    display: flex;
    align-items: end;
    justify-content: end;
  }
}
</style>
